import os
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QLabel, QMessageBox
from PyQt5.QtCore import Qt


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('单实例示例')
        self.setGeometry(100, 100, 400, 200)

        layout = QVBoxLayout()

        self.label = QLabel("欢迎使用单实例示例应用")
        self.label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.label)

        self.button = QPushButton("点击我")
        self.button.clicked.connect(self.on_button_click)
        layout.addWidget(self.button)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def on_button_click(self):
        QMessageBox.information(self, '按钮点击', '你点击了按钮')

    def closeEvent(self, event):
        # 清除文件锁
        with open('app_lock.txt', 'w') as f:
            f.write('')
        event.accept()


if __name__ == '__main__':
    lock_file = 'app_lock.txt'
    app = QApplication(sys.argv)
    # 检查是否已经有实例在运行
    if os.path.exists(lock_file):
        with open(lock_file, 'r') as f:
            content = f.read().strip()
        if content:
            QMessageBox.critical(None, '应用已运行', '该应用已经在运行，请不要重复启动。')
            sys.exit(0)

    # 设置文件锁
    with open(lock_file, 'w') as f:
        f.write('locked')


    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
